package com.java.study.invoker.config;


import com.java.study.invoker.annotation.MyLoadBalanced;
import com.java.study.invoker.enreka.interceptor.RestInterceptor;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Configuration
public class RestAutoConfiguration {

    @Autowired(required = false)
    @MyLoadBalanced
    private List<RestTemplate> restTemplateList = Collections.emptyList();


    @Bean
    public SmartInitializingSingleton myLoadBalanceRestTemplateInitializer() {
        System.out.println("==== 这个 Bean 将在容器初始化时创建 =====");
        return new SmartInitializingSingleton() {

            @Override
            public void afterSingletonsInstantiated() {
                for (RestTemplate tpl : restTemplateList) {
                    // 创建一个自定义的拦截器实例
                    RestInterceptor mi = new RestInterceptor();
                    // 获取 RestTemplate 原来的拦截器
                    List list = new ArrayList(tpl.getInterceptors());
                    // 添加到拦截器集合
                    list.add(mi);
                    // 将新的拦截器集合设置到 RestTemplate 实例
                    tpl.setInterceptors(list);
                }
            }
        };
    }
}


